package org.soma.sso.core.filter;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.soma.sso.core.utils.SsoUtils;
import org.springframework.beans.factory.annotation.Autowired;

public class SomaSsoCookieFilter extends HttpServlet implements Filter {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 5716474080011059081L;
	public static Logger logger = LoggerFactory.getLogger(SomaSsoFilter.class);

	private String SSO_SERVER_URL;
	private String SSO_SERVER_VERIFY_URL;

	public void init(FilterConfig filterConfig) throws ServletException {
		SSO_SERVER_URL = filterConfig.getInitParameter("SSO_SERVER_URL");
		SSO_SERVER_VERIFY_URL = filterConfig
				.getInitParameter("SSO_SERVER_VERIFY_URL");
		if (StringUtils.isBlank(SSO_SERVER_URL)) {
			logger.error("SSO_SERVER_URL is null.");
		}
		if (StringUtils.isBlank(SSO_SERVER_VERIFY_URL)) {
			logger.error("SSO_SERVER_VERIFY_URL is null.");
		}
	}

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain chain)
		throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		String cookieSessionId = SsoUtils.getSessionIdByCookie(request);
		String callback = request.getRequestURL().toString();
		System.out.println(callback);
		if(cookieSessionId!=null && callback.contains("login.html")){
			chain.doFilter(request, response);
		}else{
			 //跳转至sso认证中心
			 String callbackURL = request.getRequestURL().toString();
			 StringBuilder url = new StringBuilder();
			 url.append(SSO_SERVER_URL).append("?callbackURL=").append(callbackURL);
			 response.sendRedirect(url.toString());
		}
	}



	public void destroy() {
		// TODO Auto-generated method stub

	}

}
